package com.centling.smartSealForPhone.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.View
import com.centling.smartSealForPhone.R
import com.centling.smartSealForPhone.bean.DetailBean
import com.centling.smartSealForPhone.bean.DeviceTypeBean
import com.centling.smartSealForPhone.fragment.StampActivity
import com.centling.smartSealForPhone.constants.GlobalData
import com.centling.smartSealForPhone.constants.SPConstants
import com.centling.smartSealForPhone.constants.UrlConstants
import com.centling.smartSealForPhone.constants.UserType
import com.centling.smartSealForPhone.utils.ImageUtil
import com.centling.smartSealForPhone.utils.OkHttpUtil
import com.centling.smartSealForPhone.utils.SPUtil
import com.centling.smartSealForPhone.utils.ShowToast
import com.example.localalbum.common.LocalImageHelper
import com.example.localalbum.ui.PagerView
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_stamp_detail.*
import java.io.Serializable
import java.util.*

class StampDetailActivity : TitleBarActivity() {

    private var bean: DetailBean? = null
    private val userImgs = ArrayList<String>()
    private val fileImgs = ArrayList<String>()

    private var deviceTypeBean: DeviceTypeBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stamp_detail)

        setTitleBarText("用印详情")

        sendRequestToFetchInfo()
    }

    private fun sendRequestToFetchInfo() {
        mProcessDialog.setTitle("正在获取详情").showNormal()
        getEnqueue(String.format(Locale.CHINA, UrlConstants.DETAIL_NEW,
                intent.getStringExtra("sealApplyId")), object : OkHttpUtil.NetCallBack {
            override fun onSucceed(json: String) {
                mProcessDialog.dismiss()
                bean = Gson().fromJson(json, DetailBean::class.java)
                setData(bean!!)
            }

            override fun onFailed(reason: String) {
                mProcessDialog.dismiss()
                ShowToast.shortTime(reason)
                finish()
            }
        })
    }

    @SuppressLint("SetTextI18n")
    private fun setData(bean: DetailBean) {
        if (bean.isValid == "0") {
            tv_stamp_detail_is_valid.text = "正常"
        } else {
            tv_stamp_detail_is_valid.text = "换章失效"
            tv_stamp_detail_start_stamp.visibility = View.GONE
        }

        tv_stamp_detail_apply_name.text = bean.applyOperator
        tv_stamp_detail_seal_reg.text = bean.sealReg
        tv_stamp_detail_user_name.text = bean.applicantUserName
        tv_stamp_detail_start_stamp.visibility =
                if (TextUtils.equals(bean.embedEquipOutFlag, "1"))
                    if (TextUtils.equals(bean.applyCreatorTypeFlag, UserType.EQUIP_COMMON_USER)
                            && !TextUtils.equals(SPUtil.getString(SPConstants.USER_TYPE), UserType.EQUIP_COMMON_USER))
                        View.GONE
                    else
                        View.VISIBLE
                else
                    View.GONE

        if (TextUtils.equals(bean.applyType, "COUNT_LIMIT")) {
            ll_stamp_detail_use_times.visibility = View.VISIBLE
            ll_stamp_detail_apply_date.visibility = View.VISIBLE
            tv_stamp_detail_use_times.text = "${bean.applyTimes}"
            tv_stamp_detail_remain_times.text = "${bean.remainTimes}"
            tv_stamp_detail_apply_date.text = bean.applyDate
            tv_stamp_detail_start_stamp.setOnClickListener {
                sendRequestToCheckIsUse(bean, 0)
            }
        } else {
            ll_stamp_detail_start_date.visibility = View.VISIBLE
            ll_stamp_detail_end_date.visibility = View.VISIBLE
            tv_stamp_detail_start_date.text = bean.applyStartTimeReal
            tv_stamp_detail_end_date.text = bean.applyEndTimeReal
            tv_stamp_detail_start_stamp.setOnClickListener {
                sendRequestToCheckIsUse(bean, 1)
            }
        }
        tv_stamp_detail_authorize_date.text = bean.authTimeReal
        tv_stamp_detail_use_reason.text = "${bean.applyReasonType}${if (TextUtils.isEmpty(bean.applyReason)) "" else ":" }${bean.applyReason}"

        tv_stamp_detail_approval_history.setOnClickListener {
            if (bean.sealApplyAuditRecordList != null && !bean.sealApplyAuditRecordList.isEmpty()) {
                startActivity(Intent(mContext, HistoryApprovalRecordsActivity::class.java).putParcelableArrayListExtra("history_stamp_records", bean.sealApplyAuditRecordList as ArrayList<out Parcelable>))
            } else {
                ShowToast.shortTime("没有审阅记录")
            }
        }

        userImgs.add(bean.applicantUserAvatar)
        ImageUtil.loadImage(userImgs[0], scroll_img_user, R.drawable.iv_avatar_default)
        scroll_img_user.setOnClickListener {
            val pictures: MutableList<LocalImageHelper.LocalFile> = ArrayList()
            val file = LocalImageHelper.LocalFile()
            file.originalUri = userImgs[0]
            file.thumbnailUri = userImgs[0]
            pictures.add(file)
            val intent = Intent(mContext, PagerView::class.java)
            intent.putExtra("FILE_LIST", pictures as Serializable)
            intent.putExtra("INDEX", 0)
            mContext.startActivity(intent)
        }
        val files = bean.docPics.split(",".toRegex()).dropLastWhile(String::isEmpty).toTypedArray()
        fileImgs += files
        scroll_img_file.addFiles(fileImgs)
    }

    private fun sendRequestToCheckIsUse(rowsBean: DetailBean, type: Int) {
        getEnqueue(String.format(Locale.CHINA, UrlConstants.GET_DEVICE_STATE_NEW + "?embenedSn=%s",
                GlobalData.USESEAL, rowsBean.embenedSn),
                object : OkHttpUtil.NetCallBack {
                    override fun onSucceed(json: String) {
                        deviceTypeBean = Gson().fromJson(json, DeviceTypeBean::class.java)
                        if (deviceTypeBean?.isAllowed == true) {
                            clickToStamp(type)
                        } else {
                            ShowToast.shortTime(deviceTypeBean?.message)
                        }
                    }

                    override fun onFailed(reason: String) {
                        ShowToast.shortTime(reason)
                    }
                })
    }

    private fun clickToStamp(type: Int) {
        if (type == 0) {
            val intent = Intent(mContext, StampActivity::class.java)
            intent.putExtra("sealApplyId", bean!!.sealApplyId)
            intent.putExtra("macAddress", bean!!.sealEquipBlueToothMac)
            intent.putExtra("equipSn", bean!!.embenedSn)
            mContext.startActivity(intent)
        } else {
            sendRequestToGetTimes(bean!!.sealApplyId)
        }
    }

    private fun sendRequestToGetTimes(id: String) {
        mProcessDialog.setTitle("正在获取用印信息").showNormal()
        getEnqueue(String.format(Locale.CHINA, UrlConstants.GET_STAMP_REMAIN_TIMES_NEW, id),
                object : OkHttpUtil.NetCallBack {
                    override fun onSucceed(json: String) {
                        mProcessDialog.dismiss()
                        val intent = Intent(mContext, StampTimeLimitActivity::class.java)
                        intent.putExtra("sealApplyId", bean!!.sealApplyId)
                        intent.putExtra("macAddress", bean!!.sealEquipBlueToothMac)
                        intent.putExtra("equipSn", bean!!.embenedSn)
                        intent.putExtra("sealApplyStartTime", bean!!.applyStartTimeReal)
                        intent.putExtra("sealApplyEndTime", bean!!.applyEndTimeReal)
                        mContext.startActivity(intent)
                    }

                    override fun onFailed(reason: String) {
                        mProcessDialog.dismiss()
                        ShowToast.shortTime(reason)
                    }
                })
    }
}
